/**
 * @version Create on 2012-10-29
 * @author Yinzi Chen
 */

public class AddTwoNumbers {

	class ListNode {
		int val;
		ListNode next;

		ListNode(int x) {
			val = x;
			next = null;
		}
	}

	public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		ListNode head = new ListNode(0);
		ListNode cur = head;
		while (l1 != null || l2 != null) {
			if (l1 != null) {
				if (cur.next == null) {
					cur.next = new ListNode(l1.val);
				} else {
					cur.next.val += l1.val;
				}
				if (cur.next.val >= 10) {
					cur.next.next = new ListNode(1);
					cur.next.val -= 10;
				}
				l1 = l1.next;
			}
			if (l2 != null) {
				if (cur.next == null) {
					cur.next = new ListNode(l2.val);
				} else {
					cur.next.val += l2.val;
				}
				if (cur.next.val >= 10) {
					cur.next.next = new ListNode(1);
					cur.next.val -= 10;
				}
				l2 = l2.next;
			}
			cur = cur.next;
		}
		return head.next;
	}

	public static void main(String[] args) {

	}

}
